<template>
  <view class="container">
    <view class="header">
      <text class="title">API接口测试</text>
    </view>
    
    <view class="test-section">
      <text class="section-title">🔧 基础测试</text>
      
      <button class="test-btn" @tap="testHealth">
        测试健康检查 (GET /test/health)
      </button>
      
      <button class="test-btn" @tap="testHello">
        测试Hello接口 (GET /test/hello)
      </button>
      
      <button class="test-btn" @tap="testInvalidEndpoint">
        测试无效接口 (测试错误处理)
      </button>
    </view>
    
    <view class="test-section">
      <text class="section-title">🔐 认证接口测试</text>
      
      <button class="test-btn auth-btn" @tap="testRegister">
        测试用户注册 (POST /auth/register)
      </button>
      
      <button class="test-btn auth-btn" @tap="testLogin">
        测试用户登录 (POST /auth/login)
      </button>
      
      <button class="test-btn auth-btn" @tap="testProfile">
        测试获取用户信息 (GET /auth/profile)
      </button>
      
      <button class="test-btn danger-btn" @tap="testLogout">
        测试登出 (清除本地数据)
      </button>
    </view>
    
    <view class="test-section">
      <text class="section-title">📍 地址管理测试</text>
      
      <button class="test-btn address-btn" @tap="testGetAddressList">
        获取地址列表 (GET /user/addresses)
      </button>
      
      <button class="test-btn address-btn" @tap="testAddAddress">
        添加地址 (POST /user/addresses)
      </button>
      
      <button class="test-btn address-btn" @tap="testGetDefaultAddress">
        获取默认地址 (GET /user/addresses/default)
      </button>
      
      <button class="test-btn address-btn" @tap="testSetDefaultAddress">
        设置默认地址 (PUT /user/addresses/{id}/default)
      </button>
      
      <button class="test-btn danger-btn" @tap="testDeleteAddress">
        删除地址 (DELETE /user/addresses/{id})
      </button>
      
      <button class="test-btn debug-btn" @tap="debugAddAddress">
        🐛 调试添加地址（原始请求）
      </button>
      
      <button class="test-btn debug-btn" @tap="debugAddAddressV2">
        🐛 调试添加地址V2（Postman格式）
      </button>
      
      <button class="test-btn debug-btn" @tap="testJWTAuth">
        🔑 测试JWT认证（获取用户信息）
      </button>
      
      <button class="test-btn debug-btn" @tap="debugAddAddressV3">
        🐛 调试V3（简化数据）
      </button>
      
      <button class="test-btn debug-btn" @tap="debugAddAddressV4">
        🐛 调试V4（字段测试）
      </button>
    </view>
    
    <view class="log-section">
      <text class="section-title">📋 测试日志</text>
      <view class="log-container">
        <text v-for="(log, index) in logs" :key="index" class="log-item">
          {{ log }}
        </text>
      </view>
      <view class="log-buttons">
        <button class="clear-btn" @tap="clearLogs">清空日志</button>
        <button class="copy-btn" @tap="copyLogs">复制日志</button>
      </view>
    </view>
  </view>
</template>

<script>
import http from '../../services/api.js'
import authService from '../../services/auth.js'
import addressService from '../../services/address.js'
import foodService from '../../services/food.js'
import merchantService from '../../services/merchant.js'

export default {
  data() {
    return {
      logs: [],
      lastRegisteredUser: null, // 保存最后注册的用户信息
      lastAddedAddressId: null // 保存最后添加的地址ID
    }
  },
  
  methods: {
    // 添加日志
    addLog(message) {
      const timestamp = new Date().toLocaleTimeString()
      this.logs.unshift(`[${timestamp}] ${message}`)
      
      // 限制日志数量
      if (this.logs.length > 20) {
        this.logs = this.logs.slice(0, 20)
      }
    },
    
    // 清空日志
    clearLogs() {
      this.logs = []
    },
    
    // 复制日志
    copyLogs() {
      if (this.logs.length === 0) {
        uni.showToast({
          title: '没有日志可复制',
          icon: 'error',
          duration: 1500
        })
        return
      }
      
      const logText = this.logs.join('\n')
      
      // 尝试使用剪贴板API
      if (navigator.clipboard) {
        navigator.clipboard.writeText(logText).then(() => {
          uni.showToast({
            title: '日志已复制到剪贴板',
            icon: 'success',
            duration: 2000
          })
        }).catch(() => {
          this.fallbackCopyLogs(logText)
        })
      } else {
        this.fallbackCopyLogs(logText)
      }
    },
    
    // 备用复制方法
    fallbackCopyLogs(text) {
      // 创建临时textarea元素
      const textarea = document.createElement('textarea')
      textarea.value = text
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      
      try {
        textarea.select()
        document.execCommand('copy')
        document.body.removeChild(textarea)
        
        uni.showToast({
          title: '日志已复制到剪贴板',
          icon: 'success',
          duration: 2000
        })
      } catch (err) {
        document.body.removeChild(textarea)
        
        // 如果复制失败，显示日志内容供手动复制
        uni.showModal({
          title: '复制日志',
          content: '请手动复制以下内容：\n\n' + text.substring(0, 500) + (text.length > 500 ? '...' : ''),
          showCancel: false,
          confirmText: '确定'
        })
      }
    },
    
    // 测试健康检查接口
    async testHealth() {
      this.addLog('开始测试健康检查接口...')
      
      try {
        const response = await http.get('/test/health', {}, {
          needAuth: false,
          showLoading: true,
          loadingText: '测试中...'
        })
        
        this.addLog(`✅ 健康检查成功: ${JSON.stringify(response)}`)
        
        uni.showToast({
          title: '健康检查成功',
          icon: 'success',
          duration: 2000
        })
        
      } catch (error) {
        this.addLog(`❌ 健康检查失败: ${error.message}`)
        
        uni.showToast({
          title: '健康检查失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 测试Hello接口
    async testHello() {
      this.addLog('开始测试Hello接口...')
      
      try {
        const response = await http.get('/test/hello', {}, {
          needAuth: false,
          showLoading: true,
          loadingText: '测试中...'
        })
        
        this.addLog(`✅ Hello接口成功: ${JSON.stringify(response)}`)
        
        uni.showToast({
          title: 'Hello接口成功',
          icon: 'success',
          duration: 2000
        })
        
      } catch (error) {
        this.addLog(`❌ Hello接口失败: ${error.message}`)
        
        uni.showToast({
          title: 'Hello接口失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 测试无效接口（测试错误处理）
    async testInvalidEndpoint() {
      this.addLog('开始测试无效接口（测试错误处理）...')
      
      try {
        const response = await http.get('/test/invalid-endpoint', {}, {
          needAuth: false,
          showLoading: true,
          loadingText: '测试中...'
        })
        
        this.addLog(`✅ 无效接口竟然成功了: ${JSON.stringify(response)}`)
        
      } catch (error) {
        this.addLog(`✅ 错误处理正常: ${error.message}`)
        
        uni.showToast({
          title: '错误处理正常',
          icon: 'success',
          duration: 2000
        })
      }
    },
    
    // 测试用户注册
    async testRegister() {
      this.addLog('开始测试用户注册...')
      
      // 生成测试用户数据
      const timestamp = Date.now()
      const testUser = {
        username: `testuser${timestamp}`,
        email: `test${timestamp}@example.com`,
        password: '123456',
        phone: '13800138000',
        realName: '测试用户'
      }
      
      this.addLog(`注册数据: ${JSON.stringify(testUser)}`)
      
      try {
        const response = await authService.register(testUser)
        
        // 保存注册的用户信息，供登录测试使用
        this.lastRegisteredUser = testUser
        
        this.addLog(`✅ 用户注册成功: ${JSON.stringify(response)}`)
        this.addLog(`✅ Token已保存: ${authService.checkLoginStatus().token ? '是' : '否'}`)
        this.addLog(`💡 可以使用此账号测试登录: ${testUser.username}`)
        
        uni.showToast({
          title: '注册成功',
          icon: 'success',
          duration: 2000
        })
        
      } catch (error) {
        this.addLog(`❌ 用户注册失败: ${error.message}`)
        
        uni.showToast({
          title: '注册失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 测试用户登录
    async testLogin() {
      this.addLog('开始测试用户登录...')
      
      let credentials
      
      // 优先使用刚注册的账号
      if (this.lastRegisteredUser) {
        credentials = {
          username: this.lastRegisteredUser.username,
          password: this.lastRegisteredUser.password,
          remember: true
        }
        this.addLog(`使用刚注册的账号: ${this.lastRegisteredUser.username}`)
      } else {
        // 使用固定的测试账号
        credentials = {
          username: 'testuser',
          password: '123456',
          remember: true
        }
        this.addLog('使用固定测试账号: testuser')
        this.addLog('💡 如果登录失败，请先测试注册功能')
      }
      
      this.addLog(`登录数据: ${JSON.stringify(credentials)}`)
      
      try {
        const response = await authService.login(credentials)
        
        this.addLog(`✅ 用户登录成功: ${JSON.stringify(response)}`)
        this.addLog(`✅ Token已保存: ${authService.checkLoginStatus().token ? '是' : '否'}`)
        
        uni.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 2000
        })
        
      } catch (error) {
        this.addLog(`❌ 用户登录失败: ${error.message}`)
        
        if (!this.lastRegisteredUser) {
          this.addLog('💡 建议：先点击"测试用户注册"创建账号，再测试登录')
        }
        
        uni.showToast({
          title: '登录失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 测试获取用户信息
    async testProfile() {
      this.addLog('开始测试获取用户信息...')
      
      const loginStatus = authService.checkLoginStatus()
      this.addLog(`当前登录状态: ${loginStatus.isLoggedIn ? '已登录' : '未登录'}`)
      
      if (!loginStatus.isLoggedIn) {
        this.addLog('❌ 请先登录')
        uni.showToast({
          title: '请先登录',
          icon: 'error',
          duration: 2000
        })
        return
      }
      
      try {
        const response = await authService.getProfile()
        
        this.addLog(`✅ 获取用户信息成功: ${JSON.stringify(response)}`)
        
        uni.showToast({
          title: '获取用户信息成功',
          icon: 'success',
          duration: 2000
        })
        
      } catch (error) {
        this.addLog(`❌ 获取用户信息失败: ${error.message}`)
        
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 测试登出
    async testLogout() {
      this.addLog('开始测试登出...')
      
      const loginStatus = authService.checkLoginStatus()
      this.addLog(`登出前状态: ${loginStatus.isLoggedIn ? '已登录' : '未登录'}`)
      
      try {
        const result = await authService.logout()
        
        if (result) {
          const newStatus = authService.checkLoginStatus()
          this.addLog(`✅ 登出成功`)
          this.addLog(`登出后状态: ${newStatus.isLoggedIn ? '已登录' : '未登录'}`)
          
          uni.showToast({
            title: '登出成功',
            icon: 'success',
            duration: 2000
          })
        } else {
          this.addLog(`❌ 登出失败`)
        }
        
      } catch (error) {
        this.addLog(`❌ 登出失败: ${error.message}`)
      }
    },
    
    // 检查登录状态
    checkAuthStatus() {
      const loginStatus = authService.checkLoginStatus()
      if (!loginStatus.isLoggedIn) {
        this.addLog('❌ 请先登录')
        uni.showToast({
          title: '请先登录',
          icon: 'error',
          duration: 2000
        })
        return false
      }
      return true
    },
    
    // 测试获取地址列表
    async testGetAddressList() {
      this.addLog('开始测试获取地址列表...')
      
      if (!this.checkAuthStatus()) return
      
      try {
        const response = await addressService.getAddressList()
        
        this.addLog(`✅ 获取地址列表成功: ${JSON.stringify(response)}`)
        
        if (response.data && Array.isArray(response.data)) {
          this.addLog(`📍 共有 ${response.data.length} 个地址`)
        }
        
        uni.showToast({
          title: '获取地址列表成功',
          icon: 'success',
          duration: 2000
        })
        
      } catch (error) {
        this.addLog(`❌ 获取地址列表失败: ${error.message}`)
        
        uni.showToast({
          title: '获取地址列表失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 测试添加地址
    async testAddAddress() {
      this.addLog('开始测试添加地址...')
      
      if (!this.checkAuthStatus()) return
      
      // 使用正确的数据格式（isDefault为数字）
      const testAddress = {
        name: '李四',
        phone: '13800138002',
        province: '广东省',
        city: '深圳市',
        district: '福田区',
        address: '华强北路2号B座15楼',
        isDefault: 0  // 使用数字格式而不是布尔值
      }
      
      this.addLog(`📋 地址数据: ${JSON.stringify(testAddress, null, 2)}`)
      this.addLog(`🔍 数据验证结果: ${JSON.stringify(addressService.validateAddress(testAddress))}`)
      
      try {
        this.addLog('🚀 发送请求到 POST /api/v1/user/addresses')
        const response = await addressService.addAddress(testAddress)
        
        this.addLog(`✅ 添加地址成功`)
        this.addLog(`📄 完整响应: ${JSON.stringify(response, null, 2)}`)
        
        // 保存地址ID供后续测试使用
        if (response.data && response.data.id) {
          this.lastAddedAddressId = response.data.id
          this.addLog(`💾 地址ID已保存: ${this.lastAddedAddressId}`)
        } else if (response.data) {
          this.addLog(`⚠️ 响应中未找到地址ID，完整data: ${JSON.stringify(response.data)}`)
        }
        
        uni.showToast({
          title: '添加地址成功',
          icon: 'success',
          duration: 2000
        })
        
        // 添加成功后自动获取地址列表验证
        this.addLog('🔄 自动获取地址列表验证...')
        setTimeout(() => {
          this.testGetAddressList()
        }, 1000)
        
      } catch (error) {
        this.addLog(`❌ 添加地址失败`)
        this.addLog(`🔴 错误详情: ${error.message}`)
        this.addLog(`🔴 错误对象: ${JSON.stringify(error, Object.getOwnPropertyNames(error))}`)
        
        uni.showToast({
          title: '添加地址失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 测试获取默认地址
    async testGetDefaultAddress() {
      this.addLog('开始测试获取默认地址...')
      
      if (!this.checkAuthStatus()) return
      
      try {
        const response = await addressService.getDefaultAddress()
        
        this.addLog(`✅ 获取默认地址成功: ${JSON.stringify(response)}`)
        
        uni.showToast({
          title: '获取默认地址成功',
          icon: 'success',
          duration: 2000
        })
        
      } catch (error) {
        this.addLog(`❌ 获取默认地址失败: ${error.message}`)
        
        uni.showToast({
          title: '获取默认地址失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 测试设置默认地址
    async testSetDefaultAddress() {
      this.addLog('开始测试设置默认地址...')
      
      if (!this.checkAuthStatus()) return
      
      if (!this.lastAddedAddressId) {
        this.addLog('❌ 请先添加地址')
        uni.showToast({
          title: '请先添加地址',
          icon: 'error',
          duration: 2000
        })
        return
      }
      
      this.addLog(`使用地址ID: ${this.lastAddedAddressId}`)
      
      try {
        const response = await addressService.setDefaultAddress(this.lastAddedAddressId)
        
        this.addLog(`✅ 设置默认地址成功: ${JSON.stringify(response)}`)
        
        uni.showToast({
          title: '设置默认地址成功',
          icon: 'success',
          duration: 2000
        })
        
      } catch (error) {
        this.addLog(`❌ 设置默认地址失败: ${error.message}`)
        
        uni.showToast({
          title: '设置默认地址失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 测试删除地址
    async testDeleteAddress() {
      this.addLog('开始测试删除地址...')
      
      if (!this.checkAuthStatus()) return
      
      if (!this.lastAddedAddressId) {
        this.addLog('❌ 请先添加地址')
        uni.showToast({
          title: '请先添加地址',
          icon: 'error',
          duration: 2000
        })
        return
      }
      
      this.addLog(`删除地址ID: ${this.lastAddedAddressId}`)
      
      try {
        const response = await addressService.deleteAddress(this.lastAddedAddressId)
        
        this.addLog(`✅ 删除地址成功: ${JSON.stringify(response)}`)
        
        // 清除已删除的地址ID
        this.lastAddedAddressId = null
        
        uni.showToast({
          title: '删除地址成功',
          icon: 'success',
          duration: 2000
        })
        
      } catch (error) {
        this.addLog(`❌ 删除地址失败: ${error.message}`)
        
        uni.showToast({
          title: '删除地址失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 调试添加地址 - 原始请求
    async debugAddAddress() {
      this.addLog('🐛 开始调试添加地址（原始请求）...')
      
      if (!this.checkAuthStatus()) return
      
      const testAddress = {
        name: '李四',
        phone: '13800138002',
        province: '广东省',
        city: '深圳市',
        district: '福田区',
        address: '华强北路2号B座15楼',
        isDefault: false
      }
      
      this.addLog(`🔍 请求URL: http://localhost:8080/api/v1/user/addresses`)
      this.addLog(`🔍 请求方法: POST`)
      this.addLog(`🔍 请求头: Authorization: Bearer ${authService.checkLoginStatus().token ? 'xxx...' : '无'}`)
      this.addLog(`🔍 请求体: ${JSON.stringify(testAddress, null, 2)}`)
      
      // 使用原始uni.request来获取更详细的错误信息
      uni.request({
        url: 'http://localhost:8080/api/v1/user/addresses',
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authService.checkLoginStatus().token}`
        },
        data: testAddress,
        success: (res) => {
          this.addLog(`✅ 原始请求成功`)
          this.addLog(`📄 HTTP状态码: ${res.statusCode}`)
          this.addLog(`📄 响应头: ${JSON.stringify(res.header, null, 2)}`)
          this.addLog(`📄 响应体: ${JSON.stringify(res.data, null, 2)}`)
        },
        fail: (err) => {
          this.addLog(`❌ 原始请求失败`)
          this.addLog(`🔴 错误信息: ${JSON.stringify(err, null, 2)}`)
        },
        complete: (res) => {
          this.addLog(`📋 完整响应: ${JSON.stringify(res, null, 2)}`)
        }
      })
    },
    
    // 调试添加地址V2 - 使用Postman格式
    async debugAddAddressV2() {
      this.addLog('🐛 开始调试添加地址V2（Postman格式）...')
      
      if (!this.checkAuthStatus()) return
      
      // 使用Postman指南中的格式
      const testAddress = {
        name: '测试用户',
        phone: '13800138000',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        address: '测试地址123号',
        isDefault: true
      }
      
      this.addLog(`🔍 请求URL: http://localhost:8080/api/v1/user/addresses`)
      this.addLog(`🔍 请求方法: POST`)
      this.addLog(`🔍 请求头: Authorization: Bearer ${authService.checkLoginStatus().token ? 'xxx...' : '无'}`)
      this.addLog(`🔍 请求体（Postman格式）: ${JSON.stringify(testAddress, null, 2)}`)
      
      // 使用原始uni.request来获取更详细的错误信息
      uni.request({
        url: 'http://localhost:8080/api/v1/user/addresses',
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authService.checkLoginStatus().token}`
        },
        data: testAddress,
        success: (res) => {
          this.addLog(`✅ V2原始请求成功`)
          this.addLog(`📄 HTTP状态码: ${res.statusCode}`)
          this.addLog(`📄 响应头: ${JSON.stringify(res.header, null, 2)}`)
          this.addLog(`📄 响应体: ${JSON.stringify(res.data, null, 2)}`)
        },
        fail: (err) => {
          this.addLog(`❌ V2原始请求失败`)
          this.addLog(`🔴 错误信息: ${JSON.stringify(err, null, 2)}`)
        },
        complete: (res) => {
          this.addLog(`📋 V2完整响应: ${JSON.stringify(res, null, 2)}`)
        }
      })
    },
    
    // 测试JWT认证 - 获取用户信息
    async testJWTAuth() {
      this.addLog('🔑 测试JWT认证（获取用户信息）...')
      
      if (!this.checkAuthStatus()) return
      
      this.addLog(`🔍 请求URL: http://localhost:8080/api/v1/auth/profile`)
      this.addLog(`🔍 请求方法: GET`)
      this.addLog(`🔍 请求头: Authorization: Bearer ${authService.checkLoginStatus().token ? 'xxx...' : '无'}`)
      
      // 使用原始uni.request测试JWT认证
      uni.request({
        url: 'http://localhost:8080/api/v1/auth/profile',
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authService.checkLoginStatus().token}`
        },
        success: (res) => {
          this.addLog(`✅ JWT认证请求成功`)
          this.addLog(`📄 HTTP状态码: ${res.statusCode}`)
          this.addLog(`📄 响应体: ${JSON.stringify(res.data, null, 2)}`)
          
          if (res.statusCode === 200) {
            this.addLog(`🎉 JWT认证正常工作！`)
          } else {
            this.addLog(`⚠️ JWT认证可能有问题`)
          }
        },
        fail: (err) => {
          this.addLog(`❌ JWT认证请求失败`)
          this.addLog(`🔴 错误信息: ${JSON.stringify(err, null, 2)}`)
        },
        complete: (res) => {
          this.addLog(`📋 JWT完整响应: ${JSON.stringify(res, null, 2)}`)
        }
      })
    },
    
    // 调试添加地址V3 - 简化数据测试
    async debugAddAddressV3() {
      this.addLog('🐛 开始调试添加地址V3（简化数据）...')
      
      if (!this.checkAuthStatus()) return
      
      // 使用最简化的数据
      const testAddress = {
        name: 'Test',
        phone: '13800138000',
        province: 'Test Province',
        city: 'Test City', 
        district: 'Test District',
        address: 'Test Address',
        isDefault: false
      }
      
      this.addLog(`🔍 简化数据: ${JSON.stringify(testAddress, null, 2)}`)
      
      // 尝试不同的Content-Type
      const tests = [
        {
          name: '标准JSON',
          contentType: 'application/json',
          data: testAddress
        },
        {
          name: '表单数据',
          contentType: 'application/x-www-form-urlencoded',
          data: Object.keys(testAddress).map(key => 
            `${encodeURIComponent(key)}=${encodeURIComponent(testAddress[key])}`
          ).join('&')
        }
      ]
      
      for (let i = 0; i < tests.length; i++) {
        const test = tests[i]
        this.addLog(`🧪 测试${i+1}: ${test.name}`)
        this.addLog(`📤 Content-Type: ${test.contentType}`)
        this.addLog(`📤 数据: ${typeof test.data === 'string' ? test.data : JSON.stringify(test.data)}`)
        
        await new Promise(resolve => {
          uni.request({
            url: 'http://localhost:8080/api/v1/user/addresses',
            method: 'POST',
            header: {
              'Content-Type': test.contentType,
              'Authorization': `Bearer ${authService.checkLoginStatus().token}`
            },
            data: test.data,
            success: (res) => {
              this.addLog(`✅ ${test.name}请求成功`)
              this.addLog(`📄 状态码: ${res.statusCode}`)
              this.addLog(`📄 响应: ${JSON.stringify(res.data, null, 2)}`)
              resolve()
            },
            fail: (err) => {
              this.addLog(`❌ ${test.name}请求失败`)
              this.addLog(`🔴 错误: ${JSON.stringify(err, null, 2)}`)
              resolve()
            },
            complete: () => {
              this.addLog(`--- ${test.name}测试完成 ---`)
            }
          })
        })
        
        // 等待一下再进行下个测试
        await new Promise(resolve => setTimeout(resolve, 1000))
      }
    },
    
    // 调试添加地址V4 - 字段逐个测试
    async debugAddAddressV4() {
      this.addLog('🐛 开始调试添加地址V4（字段测试）...')
      
      if (!this.checkAuthStatus()) return
      
      // 测试不同的字段组合
      const testCases = [
        {
          name: '最小必填字段',
          data: {
            name: 'Test',
            phone: '13800138000',
            address: 'Test Address'
          }
        },
        {
          name: '添加省市区',
          data: {
            name: 'Test',
            phone: '13800138000',
            province: 'Test Province',
            city: 'Test City',
            district: 'Test District',
            address: 'Test Address'
          }
        },
        {
          name: '添加isDefault字段',
          data: {
            name: 'Test',
            phone: '13800138000',
            province: 'Test Province',
            city: 'Test City',
            district: 'Test District',
            address: 'Test Address',
            isDefault: false
          }
        },
        {
          name: '设置为默认地址',
          data: {
            name: 'Test',
            phone: '13800138000',
            province: 'Test Province',
            city: 'Test City',
            district: 'Test District',
            address: 'Test Address',
            isDefault: true
          }
        },
        {
          name: '使用数字字段',
          data: {
            name: 'Test',
            phone: '13800138000',
            province: 'Test Province',
            city: 'Test City',
            district: 'Test District',
            address: 'Test Address',
            isDefault: 0
          }
        }
      ]
      
      for (let i = 0; i < testCases.length; i++) {
        const testCase = testCases[i]
        this.addLog(`🧪 测试${i+1}: ${testCase.name}`)
        this.addLog(`📤 数据: ${JSON.stringify(testCase.data, null, 2)}`)
        
        await new Promise(resolve => {
          uni.request({
            url: 'http://localhost:8080/api/v1/user/addresses',
            method: 'POST',
            header: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${authService.checkLoginStatus().token}`
            },
            data: testCase.data,
            success: (res) => {
              this.addLog(`✅ ${testCase.name}请求成功`)
              this.addLog(`📄 状态码: ${res.statusCode}`)
              this.addLog(`📄 响应: ${JSON.stringify(res.data, null, 2)}`)
              
              if (res.statusCode === 200 || res.statusCode === 201) {
                this.addLog(`🎉 找到可用的数据格式！`)
              }
              resolve()
            },
            fail: (err) => {
              this.addLog(`❌ ${testCase.name}请求失败`)
              this.addLog(`🔴 错误: ${JSON.stringify(err, null, 2)}`)
              resolve()
            },
            complete: () => {
              this.addLog(`--- ${testCase.name}测试完成 ---`)
            }
          })
        })
        
        // 等待一下再进行下个测试
        await new Promise(resolve => setTimeout(resolve, 1000))
      }
    }
  },
  
  onLoad() {
    this.addLog('API测试页面加载完成')
    this.addLog('后端地址: http://localhost:8080/api/v1')
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.test-section {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.test-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 15rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.test-btn:last-child {
  margin-bottom: 0;
}

.log-section {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
}

.log-container {
  max-height: 600rpx;
  overflow-y: scroll;
  background: #f8f8f8;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.log-item {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
  word-break: break-all;
}

.log-buttons {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.clear-btn, .copy-btn {
  flex: 1;
  height: 60rpx;
  line-height: 60rpx;
  color: white;
  border: none;
  border-radius: 10rpx;
  font-size: 26rpx;
}

.clear-btn {
  background: #ff6b6b;
}

.copy-btn {
  background: #2196F3;
}

.auth-btn {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%) !important;
}

.danger-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5253 100%) !important;
}

.address-btn {
  background: linear-gradient(135deg, #3742fa 0%, #2f3542 100%) !important;
}

.debug-btn {
  background: linear-gradient(135deg, #ffa726 0%, #ff9800 100%) !important;
}
</style>
